import 'package:flutter/material.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/page/extension/extensionPage.dart';
import 'package:gd_assistant/page/me/minePage.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/page/user/userPage.dart';
import 'package:azlistview/azlistview.dart';
import 'package:gd_assistant/model/doctorModel.dart';
import 'package:gd_assistant/util/dataUtil.dart';
import 'package:gd_assistant/util/eventBus.dart';
import 'package:gd_assistant/util/publicUtil.dart';


class tabNavigator extends StatefulWidget {
  @override
  _tabNavigatorState createState() => _tabNavigatorState();
}

class _tabNavigatorState extends State<tabNavigator> {
  bool isDark = false;
  final _defultColor = Colors.grey;
  final _activeColor = Colors.blue;
  var currentPage = 0;
  var scaffoldKey = new GlobalKey<ScaffoldState>();

  List<DoctorModel> _doctorList = List();
  DoctorModel _selectDoctor;
  int _suspensionHeight = 40;
  int _itemHeight = 50;
  //全部：-100，已预约:300，未预约:200
  int status = -100;
  String _suspensionTag = "";

  List<Widget> _pages = [];

  @override
  void initState() {
    super.initState();
    dataUtil.context = context;
    _pages.add(extensionPage());
    _pages.add(userPage(tatalKey: scaffoldKey, screenCb: (){
       //这里再拉一次医生接口
       if (_doctorList.length == 0) {
         publicUtil.getServiceDoctor(_doctorList);
       }
    }));
    _pages.add(minePage());
    publicUtil.getServiceDoctor(_doctorList);

    EventBus().on("searchChange", (parmas){
      status = -100;
      _doctorList.forEach((doctor){
        doctor.isSelected = false;
      });
      setState(() {});
    });
  }

  void _onSusTagChanged(String tag) {
    setState(() {
      _suspensionTag = tag;
    });
  }

  Widget _buildSusWidget(String susTag) {
    return Container(
      height: _suspensionHeight.toDouble(),
      padding: const EdgeInsets.only(left: 15.0),
      color: isDark ? Colours.dark_bg_color : Color(0xfff3f4f5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xff999999),
        ),
      ),
    );
  }


  Widget _buildListItem(DoctorModel model) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        SizedBox(
          height: _itemHeight.toDouble(),
          child: Container(
            color: model.isSelected ? isDark ? Colors.white10 : Colors.blue[100] : isDark ? Colours.dark_bg_gray : Colours.bg_gray,
            child: ListTile(
              title: Text(model.name),
              selected: model.isSelected,
              onTap: () {
                _selectDoctor = model;
                _doctorList.forEach((doctor){
                  doctor.isSelected = false;
                  if (doctor.id == _selectDoctor.id) {
                    doctor.isSelected = true;
                  }
                });
                setState(() {});
              },
            ),
          ),
        )
      ],
    );
  }

  void _changeStatus(int newStatus) {
    setState(() {
      status = newStatus;
    });
  }

  void _resetStatus() {
     _selectDoctor = null;
     status = -100;
    _doctorList.forEach((doctor){
      doctor.isSelected = false;
    });
    _submit();
    setState(() {});
  }

  void _submit() {
    EventBus().emit("doctorChoose",{"status":status,"doctorId":_selectDoctor != null ? _selectDoctor.id : ""});
    Navigator.pop(context);
  }

  @override
  void dispose() {
    super.dispose();
    //widget关闭时 删除监听
    EventBus().off("searchChange");
  }
  
  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
       endDrawer: Container(
        margin: EdgeInsets.only(left: MediaQuery.of(context).size.width - 240),
        color: isDark ? Colours.dark_bg_color : Colours.bg_color,
        child: Container(
          width: 240,
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top + 18,bottom: 10),
                child: Text("预约情况",style: TextStyle(color: Colors.grey[600],fontSize: 16)),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: FlatButton(
                      color: status == -100 ? Colors.blue : isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                      textColor: status == -100 ? Colors.white : isDark ? Colors.white : Colors.black,
                      child: Text("全部"),
                      onPressed: (){
                        _changeStatus(-100);
                      },
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: FlatButton(
                      color: status == 300 ? Colors.blue : isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                      textColor: status == 300 ? Colors.white : isDark ? Colors.white : Colors.black,
                      child: Text("已预约"),
                      onPressed: (){
                        _changeStatus(300);
                      },
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: FlatButton(
                      color: status == 200 ? Colors.blue : isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                      textColor: status == 200 ? Colors.white : isDark ? Colors.white : Colors.black,
                      child: Text("未预约"),
                      onPressed: (){
                        _changeStatus(200);
                      },
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(top: 10,bottom: 10),
                child: Text("提供服务的医生",style: TextStyle(color: Colors.grey[600],fontSize: 16)),
              ),
              Expanded(
                flex: 1,
                child: AzListView(
                  data: _doctorList,
                  itemBuilder: (context, model) => _buildListItem(model),
                  suspensionWidget: _buildSusWidget(_suspensionTag),
                  isUseRealIndex: true,
                  itemHeight: _itemHeight,
                  suspensionHeight: _suspensionHeight,
                  onSusTagChanged: _onSusTagChanged,
                ),
              ),
              Container(
                height: MediaQuery.of(context).padding.bottom + 62,
                padding: EdgeInsets.only(left: 15,right: 15,top: 0),
                child: Row(
                  children: <Widget>[
                     Expanded(
                      flex: 1,
                      child: FlatButton(
                        color:  isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                         shape: StadiumBorder(side: BorderSide.none),
                        textColor: Colors.blue,
                        child: Text("重置"),
                        onPressed: _resetStatus,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 20),
                    ),
                    Expanded(
                      flex: 1,
                      child: FlatButton(
                        color: Colors.blue,
                         shape: StadiumBorder(side: BorderSide.none),
                        textColor: Colors.white,
                        child: Text("确认"),
                        onPressed: _submit,
                      ),
                    ),
                  ],
                ),
              )
            ],
          )
        ),
      ),
      key: scaffoldKey,
      body: IndexedStack(
        index: currentPage,
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentPage,
        onTap: (index) async {
          setState(() {
            currentPage = index;
          });
          if (index == 2) {
            //这里得特殊处理评价分数
            dynamic result = await apiHandler.getEvaluationCount();
            if (result != null) {
              EventBus().emit("infoChange");
            }
          }
        },
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.date_range, color: currentPage == 0 ? _activeColor : _defultColor),title: Text("预约",style: TextStyle(color: currentPage == 0 ? _activeColor : _defultColor))),
          BottomNavigationBarItem(icon: Icon(Icons.people, color: currentPage == 1 ? _activeColor : _defultColor,),title: Text("用户",style: TextStyle(color: currentPage == 1 ? _activeColor : _defultColor))),
          BottomNavigationBarItem(icon: Icon(Icons.person, color: currentPage == 2 ? _activeColor : _defultColor,),title: Text("我的",style: TextStyle(color: currentPage == 2 ? _activeColor : _defultColor)))
        ],
      )
    );
  }
}